package com.zaki.filter;

import com.alibaba.fastjson.JSONObject;
import com.zaki.model.Result;
import com.zaki.utils.JWTUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 过滤器filter
 */
@Slf4j
//@WebFilter(urlPatterns = "/*")
public class DemoFilter implements Filter {
    @Override //初始化filter
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("过滤器初始化");
        Filter.super.init(filterConfig);
    }

    @Override //拦截请求
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("拦截到了请求");
        //1.获取请求的url
        HttpServletRequest req =(HttpServletRequest)servletRequest;
        HttpServletResponse res =(HttpServletResponse)servletResponse;
        String url =req.getRequestURL().toString();
        log.info("请求的url为：{}",url);
        //2.判断请求的url中是否包含login字符串，如果包含则说明是登录操作，直接放行
        if(url.contains("login")){
            //放行
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        //3.如果不是登录操作，则需要获取请求头里的jwt令牌
        String jwt =req.getHeader("token");
        //4.判断令牌是否存在，如果不存在则响应未登录给前端
        if(!StringUtils.hasLength(jwt)){
            Result error =Result.error("用户未登录");
            //把这个转成JSON格式返回
            String jsonStr =JSONObject.toJSONString(error);
            res.getWriter().write(jsonStr);
            return;
        }
        //5.解析jwt令牌，如果解析失败，返回错误信息（未登录）
        try{
            JWTUtils.parseJwt(jwt);
        }catch (Exception e){//解析失败
            e.printStackTrace();
            Result error =Result.error("用户未登录");
            //把这个转成JSON格式返回
            String jsonStr =JSONObject.toJSONString(error);
            res.getWriter().write(jsonStr);
            return;
        }
        //6.放行
        log.info("令牌合法，放行");
        filterChain.doFilter(servletRequest,servletResponse);

    }

    @Override
    public void destroy() {
        System.out.println("销毁方法");
        Filter.super.destroy();
    }
}
